package org.springframework.samples.mvc.fileupload;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.AbstractView;


@Component("imageView")
public class ImageView extends AbstractView{
	@Override
	protected void renderMergedOutputModel(Map model,
			HttpServletRequest req, HttpServletResponse res) throws Exception {
		ImageFile imageFile = (ImageFile)model.get("imageFile");
		
		// 응답 메시지에 파일의 길이를 넘겨줍니다.
		res.setContentLength(Long.valueOf(imageFile.getContentLength()).intValue());

		// 응답의 타입이 이미지임을 알려줍니다.
		res.setContentType(imageFile.getContentType());
		
		// 파일로부터 byte를 읽어옵니다.
		byte[] bytes = readFile(imageFile.getFileName());
		write(res, bytes);
	}

	/**
	 * 파일로부터 byte 배열 읽어오기 
	 */
	private byte[] readFile(String fileName) throws IOException {
		String path = ImageFile.IMAGE_DIR + fileName;
		
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
		int length = bis.available();
		byte[] bytes = new byte[length];
		bis.read(bytes);
		bis.close();
		
		return bytes;
	}

	/**
	 * 응답 OutputStream에 파일 내용 쓰기
	 */
	private void write(HttpServletResponse res, byte[] bytes) throws IOException {
		OutputStream output = res.getOutputStream();
		output.write(bytes);
		output.flush();
		
		
		
		
		
		
		
		

//		String relativeWebPath = "/WEB-INF/uploads";
//		String absoluteFilePath = request.getServletContext().getRealPath(relativeWebPath);
//		File uploadedFile = new File(absoluteFilePath, FilenameUtils.getName(name));
//
//		System.out.println("★★★ absoluteFilePath= "+absoluteFilePath);
//		System.out.println("★★★ ="+uploadedFile.getName());
//		System.out.println("★★★ ="+uploadedFile.getPath());
		
		// TODO 파일 저장 
//		ImageFile fileInfo = imageService.save(file2);
//		session.setAttribute("path",newFile.getAbsolutePath());
		
		// TODO 파일 저장 
//		Common.writeFile(content, name);
//		File savedFile = new File(sc.getRealPath("images"), name); 
		
//		File absolute = new File("/public/html/javafaq/index.html");
//		File relative = new File("html/javafaq/index.html");
////		System.out.println("★★★  getAbsolutePath=" + f.getAbsolutePath());
//		System.out.println("★★★ sc.getRealPath(\"upload\")=" +sc.getRealPath("upload"));
//		System.out.println("★★★ sc.getContextPath()=" +sc.getContextPath());
//		System.out.println("absolute: ");
//		System.out.println(absolute.getName());
//		System.out.println(absolute.getPath());
//		System.out.println("relative: ");
//		System.out.println(relative.getName());
//		System.out.println(relative.getPath());
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	}
}